package com.gg.haoqi.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gg.haoqi.BaseApp;
import com.gg.haoqi.adapter.AppBaseAdapter;
import com.gg.haoqi.bean.BaseBean;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by GG on 2015/11/9.
 */
public class AsynHttpHelper {

    private static AsynHttpHelper helper;
    private AsyncHttpClient client;

    public AsynHttpHelper() {
        client = new AsyncHttpClient();
    }

    public static AsynHttpHelper getInstance() {
        if (helper == null) {
            helper = new AsynHttpHelper();
        }
        return helper;
    }

    public <T> void get(String url, final List<T> list, final AppBaseAdapter<T> adpter, final TypeReference<BaseBean<T>> type) {
        client.get(url, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                BaseApp.getInstance().showToast("数据加载失败！");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (responseString != null) {
                    BaseBean entity = JSON.parseObject(responseString, type);
                    if (entity != null && entity.getMeta().getStatus() == 200) {
                        list.addAll(entity.getResponse());
                        adpter.notifyDataSetChanged();
                    }
                }
            }
        });
    }
}
